package org.ricks.event;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.function.IntPredicate;

/**
 * @author chenwei
 * @Description:事件处理方法
 * @date 2021/8/1820:41
 */
public class SubscriberMethod {
    private Object object;
    final Method method;
    private int[] eventMarks;//事件标识

    public SubscriberMethod(Object object,Method method, int[] eventMark) {
        this.object = object;
        this.method = method;
        this.eventMarks = eventMark;
    }

    public boolean checkParamsMatch(Object[] objects) {
        Class[] typeClasses = method.getParameterTypes();
        if(typeClasses.length != objects.length) return false;
        for (int i = 0; i < objects.length; i++) {
            Object object = objects[i];
            Class typeClass = typeClasses[i];
            return !typeClass.isAssignableFrom(object.getClass());
        }
        return true;
    }

    public boolean checkEventMark(int eventMark) {
        return Arrays.stream(eventMarks).anyMatch(new IntPredicate() {
            @Override
            public boolean test(int value) {
                return value == eventMark;
            }
        });
    }

    public void invoke(Object... objects) {
        try {
            method.invoke(object,objects);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }
}
